// 二叉树打家劫舍问题
// 测试链接 : https://leetcode.cn/problems/house-robber-iii/
public class HouseRobberIII {
    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;
    }

    //表示当前节点子树偷cur节点的最大值
    public int stealNode = 0;

    //表示当前节点子树不偷cur节点的最大值
    public int stealNodeNor = 0;


    public int rob(TreeNode root) {
        func(root);
        return Math.max(stealNode,stealNodeNor);
    }

    public void func(TreeNode cur){
        if(cur == null){
            stealNode = 0;
            stealNodeNor = 0;
        }else{
            int curStealNode = cur.val;
            int curStealNodeNor = 0;

            func(cur.left);//执行完方法后会更新全局变量stealNode 和 stealNodeNor
            curStealNode += stealNodeNor;
            curStealNodeNor += Math.max(stealNode,stealNodeNor);

            func(cur.right);//执行完方法后会更新全局变量stealNode 和 stealNodeNor
            curStealNode += stealNodeNor;
            curStealNodeNor += Math.max(stealNode,stealNodeNor);

            stealNode = curStealNode;
            stealNodeNor = curStealNodeNor;
        }
    }
}
